import 'dart:async';

import 'package:flutter/material.dart';
import '../../view_models/message/stream_socket.dart';
import 'package:provider/provider.dart';

class StreamGenerator {
  Stream<String> get stream async* {
    int i = 0;
    while (i < 3) {
      await Future.delayed(Duration(seconds: 1), () {
        i++;
      });
      yield i.toString();
    }
  }
}

class SocketClientWrapper extends StatefulWidget {
  SocketClientWrapper({Key? key}) : super(key: key);

  @override
  _SocketClientWrapperState createState() => _SocketClientWrapperState();
}

class _SocketClientWrapperState extends State<SocketClientWrapper> {
  final StreamSocket<String> streamSocket = StreamSocket(
      host: '127.0.0.1', port: 3001, recvEvent: 'msg', userId: 'user1');
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stream Provicer'),
      ),
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          StreamProvider<String>(
            create: (context) => streamSocket.getResponse,
            initialData: '',
            child: StreamDemo(),
          ),
          ChangeNotifierProvider<MessageModel>(
            child: MessageReplyBar(messageSendHandler: (message) {
              streamSocket.sendMessage('msg', message);
            }),
            create: (context) => MessageModel(),
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    streamSocket.connectAndListen();
    super.initState();
  }

  @override
  void dispose() {
    streamSocket.close();
    super.dispose();
  }
}

class StreamDemo extends StatelessWidget {
  StreamDemo({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        context.watch<String>(),
        style: TextStyle(
            color: Colors.blue, fontSize: 30, fontWeight: FontWeight.bold),
      ),
    );
  }
}

class MessageReplyBar extends StatelessWidget {
  final ValueChanged<String> messageSendHandler;
  const MessageReplyBar({required this.messageSendHandler, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue[400],
      width: MediaQuery.of(context).size.width,
      height: 80,
      padding: EdgeInsets.fromLTRB(
          20, 10, 20, MediaQuery.of(context).viewInsets.bottom > 0 ? 10 : 20),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              onChanged: (value) {
                context.read<MessageModel>().message = value;
              },
              decoration: InputDecoration(
                hintText: '输入消息',
                fillColor: Colors.white,
                filled: true,
                border: InputBorder.none,
              ),
            ),
          ),
          IconButton(
            onPressed: () {
              messageSendHandler(context.read<MessageModel>().message);
            },
            icon: Icon(
              Icons.near_me,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}
